﻿using Microsoft.EntityFrameworkCore.Infrastructure;

namespace Away.Configs;

public sealed class DbConfigurationService
{
    public Dictionary<string, string?> Data { get; private set; }


    private readonly DbConfigurationSource _source;
    public DbConfigurationService(DbConfigurationSource source)
    {
        _source = source;

        Data = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
        Load();
    }

    private static readonly YamlConfigurationParser _yamlParser;
    static DbConfigurationService()
    {
        _yamlParser = new YamlConfigurationParser();
    }
    
    private void Load()
    {
        using var db = new ConfigsDbContext(_source.Options);
        var configRepository = db.GetService<IConfigRepository>();
        var list = configRepository.GetConfigList(_source.Environment);

        foreach (var model in list)
        {
            switch (model.ValueType)
            {
                case 0:
                    Add(model.Key, model.Value);
                    break;
                case 1:
                case 2:
                    AddJsonOrYaml(model);
                    break;
            }
        }
    }

    private void Add(string key, string? value)
    {
        Data.Add(key, value);
    }

    private void AddJsonOrYaml(Configuration model)
    {
        var dic = _yamlParser.Parse(model.Value);
        foreach (var (k, v) in dic)
        {
            Add($"{model.Key}:{k}", v);
        }
    }
}
